package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.attr.AttrValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.atguigu.lease.web.admin.vo.room.RoomDetailVo;
import com.atguigu.lease.web.admin.vo.room.RoomItemVo;
import com.atguigu.lease.web.admin.vo.room.RoomQueryVo;
import com.atguigu.lease.web.admin.vo.room.RoomSubmitVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.Period;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【room_info(房间信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class RoomInfoServiceImpl extends ServiceImpl<RoomInfoMapper, RoomInfo>
        implements RoomInfoService {
    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    private GraphInfoMapper graphInfoMapper;
    @Autowired
    private AttrValueMapper attrValueMapper;
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private PaymentTypeMapper paymentTypeMapper;
    @Autowired
    private LeaseTermMapper leaseTermMapper;
    //注入什么看查询的这个方法的类里有什么属性，需要自定义sql的时候就注入Mapper，
    // 由它本身由这个方法和需要批处理的时候就注入service

    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private RoomAttrValueService roomAttrValueService;
    @Autowired
    private RoomFacilityService roomFacilityService;
    @Autowired
    private RoomLabelService roomLabelService;
    @Autowired
    private RoomPaymentTypeService roomPaymentTypeService;
    @Autowired
    private RoomLeaseTermService roomLeaseTermService;
    @Autowired
    private LeaseAgreementMapper leaseAgreementMapper;

    /**
     * 根据条件分页查询房间列表
     * @param roomItemVoPage
     * @param queryVo
     * @return
     */
    @Override
    public Page<RoomItemVo> pageRoomItemVO(Page<RoomItemVo> roomItemVoPage, RoomQueryVo queryVo) {

        return baseMapper.selectRoomItemList(roomItemVoPage, queryVo);
    }

    /**
     * 根据id获取房间详细信息
     *
     * @param id
     * @return
     */
    @Override
    public RoomDetailVo getRoomDetailVOById(Long id) {

        //调用Mybatis-plus 的service中自带的方法， 查询房间基本信息
        RoomInfo roomInfo = this.getById(id);

        //2.查询公寓基本信息，根据roomInfo的所示公寓id
        ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(roomInfo.getApartmentId());

        //3.查询图片列表信息
        List<GraphVo> graphVoList = graphInfoMapper.selectGraphVOByRoomIdAndItemTypeId(id, ItemType.ROOM);

        //4.查询属性信息列表
        List<AttrValueVo> attrValueVoList = attrValueMapper.selectAttrValueListByRoomId(id);

        //5.查询房间配套信息
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectFacilityInfoListByRoomId(id);

        //6.查询房间标签信息
        List<LabelInfo> labelInfoList = labelInfoMapper.selectLabelInfoListByRoomId(id);

        //7.查询支付方式列表
        List<PaymentType> paymentTypeList = paymentTypeMapper.selectPaymentTypeListByRoomId(id);
        //8.查询租期列表
        List<LeaseTerm> leaseTermList = leaseTermMapper.selectLeaseTermListByRoomId(id);

        //封装RoomDetailVo, 包含了RoomInfo基本信息
        RoomDetailVo roomDetailVo = new RoomDetailVo();
        BeanUtils.copyProperties(roomInfo, roomDetailVo);

        roomDetailVo.setApartmentInfo(apartmentInfo);
        roomDetailVo.setGraphVoList(graphVoList);
        roomDetailVo.setAttrValueVoList(attrValueVoList);
        roomDetailVo.setFacilityInfoList(facilityInfoList);
        roomDetailVo.setLabelInfoList(labelInfoList);
        roomDetailVo.setPaymentTypeList(paymentTypeList);
        roomDetailVo.setLeaseTermList(leaseTermList);
        return roomDetailVo;
    }

    /**
     * 保存或更新房间信息
     * 更新的逻辑是 删除以前所有的数据，然后直接根据id重新新增
     *
     * @param roomSubmitVo
     */
    @Override
    public void saveOrUpdateRoomInfo(RoomSubmitVo roomSubmitVo) {
        Long id = roomSubmitVo.getId();
        //获取id在前，有id 是更新，无id是保存
        this.saveOrUpdate(roomSubmitVo);
        if (id != null) {
            //2. 更新 ，当下采取的方案是：删除所有关联的数据，重新填写一边
            //2.1 根据房间id和图片类型 删除图片信息
            graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId,id));
            //2.2根据房间id 删除属性信息
           roomAttrValueService.remove(new LambdaQueryWrapper<RoomAttrValue>().eq(RoomAttrValue::getRoomId,id));

            //2.3根据房间id 删除配套信息列表
            roomFacilityService.remove(new LambdaQueryWrapper<RoomFacility>().eq(RoomFacility::getRoomId,id));

            //2.4根据房间id 删除标签信息
            roomLabelService.remove(new LambdaQueryWrapper<RoomLabel>().eq(RoomLabel::getRoomId,id));

            //2.5 根据房间id 删除支付方式信息
            roomPaymentTypeService.remove(new LambdaQueryWrapper<RoomPaymentType>().eq(RoomPaymentType::getRoomId, id));

            //2.6 根据房间id 删除租期信息
            roomLeaseTermService.remove(new LambdaQueryWrapper<RoomLeaseTerm>().eq(RoomLeaseTerm::getRoomId,id));

        }

        //3.新增需要批处理 只有service有批处理 ，mapper没有，因为用service
        //3.1 添加GraphInfoList 批处理
        //保存房间图片信息  GrapVo是前端传过来的。需要自行构建GraphInfo实体类对象。设置所属图片类型为房间  房间的id
        List<GraphVo> graphVoList = roomSubmitVo.getGraphVoList();
        //判断房间图片信息是否为空
        if (!CollectionUtils.isEmpty(graphVoList)){
            //创建房间图片表的集合
            List<GraphInfo> graphInfoList = new ArrayList<>();

            //遍历 graphVoList集合 取出配套的id
            for (GraphVo graphVo : graphVoList) {
                //构建 GraphInfo对象
                GraphInfo graphInfo = new GraphInfo();

                //设置图片名称
                graphInfo.setName(graphVo.getName());

                //设置图片所属类型为房间
                graphInfo.setItemType(ItemType.ROOM);
                //设置图片所属的对象id 公寓或房间的id
                graphInfo.setItemId(id);

                //设置图片url
                graphInfo.setUrl(graphVo.getUrl());
                //添加graphInfo
                graphInfoList.add(graphInfo);
            }
            //批量添加
            graphInfoService.saveBatch(graphInfoList);
        }

        //3.2添加房间属性信息
        //保存房间属性id
        List<Long> attrValueIds = roomSubmitVo.getAttrValueIds();
        //判断房间属性id集合是否为空
        if (!CollectionUtils.isEmpty(attrValueIds)){
            //创建房间和属性关联的集合
            List<RoomAttrValue> roomAttrValueList = new ArrayList<>();
            //遍历 取出id
            for (Long attrValueId : attrValueIds) {

            //创RoomAttrValue建对象
                RoomAttrValue roomAttrValue = RoomAttrValue.builder().roomId(roomSubmitVo.getId())
                        .attrValueId(attrValueId).build();
                roomAttrValueList.add(roomAttrValue);
            }
            roomAttrValueService.saveBatch(roomAttrValueList);
        }

        //3.3批量添加房间配套信息
        List<Long> facilityInfoIds = roomSubmitVo.getFacilityInfoIds();

        if (!CollectionUtils.isEmpty(facilityInfoIds)){
            //创建房间和配套信息的关联表集合
            List<RoomFacility> roomFacilityList = new ArrayList<>();

            for (Long facilityInfoId : facilityInfoIds) {
                RoomFacility roomFacility = RoomFacility.builder().roomId(roomSubmitVo.getId())
                        .facilityId(facilityInfoId).build();
                roomFacilityList.add(roomFacility);
            }
            roomFacilityService.saveBatch(roomFacilityList);
        }

        //3.4批量添加房间和标签信息
        List<Long> labelInfoIds = roomSubmitVo.getLabelInfoIds();

        if (!CollectionUtils.isEmpty(labelInfoIds)){

            List<RoomLabel> roomLabelList = new ArrayList<>();
            for (Long labelInfoId : labelInfoIds) {

                RoomLabel roomLabel = RoomLabel.builder().roomId(roomSubmitVo.getId()).
                        labelId(labelInfoId).build();

                roomLabelList.add(roomLabel);
            }
            roomLabelService.saveBatch(roomLabelList);
        }

        //3.5批量添加支付方式信息

        //获取支付方式信息的id
        List<Long> paymentTypeIds = roomSubmitVo.getPaymentTypeIds();

        if (!CollectionUtils.isEmpty(paymentTypeIds)){
            List<RoomPaymentType> roomPaymentTypeList = new ArrayList<>();

            for (Long paymentTypeId : paymentTypeIds) {
                RoomPaymentType roomPaymentType = RoomPaymentType.builder().roomId(roomSubmitVo.getId())
                                .paymentTypeId(paymentTypeId).build();
                roomPaymentTypeList.add(roomPaymentType);
            }
            roomPaymentTypeService.saveBatch(roomPaymentTypeList);
        }

        //3.6  批量添加房间租期信息

        List<Long> leaseTermIds = roomSubmitVo.getLeaseTermIds();
        if (!CollectionUtils.isEmpty(leaseTermIds)){
            List<RoomLeaseTerm> roomLeaseTermList = new ArrayList<>();

            for (Long leaseTermId : leaseTermIds) {
                //创RoomLeaseTerm 建对象
                RoomLeaseTerm roomLeaseTerm = RoomLeaseTerm.builder().roomId(roomSubmitVo.getId())
                                .leaseTermId(leaseTermId).build();
                roomLeaseTermList.add(roomLeaseTerm);
            }
            roomLeaseTermService.saveBatch(roomLeaseTermList);
        }
    }

    /**
     * 根据id删除房间信息
     * @param id
     */
    @Override
    public void removeRoomInfoByid(Long id) {
        //1.根据房间id 查询租约信息表，查看房间是否入住 是否在签约、续约状态
        Long count = leaseAgreementMapper.selectCount(new LambdaQueryWrapper<LeaseAgreement>()
                .eq(LeaseAgreement::getRoomId,id).in(LeaseAgreement::getStatus,2,5,7));
        System.out.println(count);
        if (count > 0 ){
            throw new LeaseException(ResultCodeEnum.APARTMENT_HAS_ROOM_HAS_PEOPLE);
        }

        this.removeById(id);

        //3.删除关联关系
        //3.1 根据房间id和图片类型 删除图片信息
        graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId,id).eq(GraphInfo::getItemType,ItemType.ROOM));

        //3.2 根据房间id删除属性信息
        roomAttrValueService.remove(new LambdaQueryWrapper<RoomAttrValue>().eq(RoomAttrValue::getRoomId,id));

        //3.3 根据房间id删除配套信息
        roomFacilityService.remove(new LambdaQueryWrapper<RoomFacility>().eq(RoomFacility::getRoomId,id));

        //3.4 根据房间id删除标签信息
        roomLabelService.remove(new LambdaQueryWrapper<RoomLabel>().eq(RoomLabel::getRoomId,id));

        //3.5 根据房间id删除租期信息
        roomLeaseTermService.remove(new LambdaQueryWrapper<RoomLeaseTerm>().eq(RoomLeaseTerm::getRoomId,id));

        //3.6 根据房间id删除支付方式信息
        roomPaymentTypeService.remove(new LambdaQueryWrapper<RoomPaymentType>().eq(RoomPaymentType::getRoomId,id));

    }
}




